package com.aiyige.page.my.download.util;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Log;

import com.aiyige.MyApp;
import com.aiyige.R;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.base.db.DBHelper;
import com.aiyige.base.db.dao.DownloadFileDao;
import com.aiyige.base.db.dao.DownloadModelDao;
import com.aiyige.base.db.table.DownloadFile;
import com.aiyige.base.db.table.DownloadModel;
import com.aiyige.base.eventbus.EventRemovalSuccess;
import com.aiyige.configs.MyConfig;
import com.aiyige.model.User;
import com.aiyige.model.moment.entity.Moment;
import com.aiyige.model.moment.entity.SingleVideo;
import com.aiyige.model.moment.entity.Video;
import com.aiyige.model.moment.entity.VideoCourse;
import com.aiyige.page.my.download.service.DownloadService;
import com.aiyige.page.my.settings.ConfigUltis;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.FileUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.MediaUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.UUIDUtil;
import com.aiyige.utils.dialog.LoadingDialog;
import com.aiyige.utils.removal.model.VideoCacheChildModel;
import com.aiyige.utils.removal.model.VideoCacheParentModel;
import com.aiyige.utils.widget.GprsNotificationDialogUtil;
import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.j256.ormlite.misc.TransactionManager;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.UpdateBuilder;
import com.vondear.rxtools.RxFileTool;
import com.vondear.rxtools.RxNetTool;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Callable;

import okhttp3.ResponseBody;
import retrofit2.Response;
import timber.log.Timber;

/**
 * Created by zhuyakun on 2017/11/29.
 */

public class DownloadUtil {
    public static final int CONTROL_OPTION_DOWNLOAD = 1;
    public static final int CONTROL_OPTION_PAUSE = 2;
    public static final int CONTROL_OPTION_DELETE = 3;
    public static final int CONTROL_OPTION_DELETE_RECORD_ONLY = 4;

    public static final long SCAN_INTERVAL_MS = 1000;
    public static final long DOWNLOAD_IDLE_TIMEOUT_MS = 5 * 60 * 1000;
    public static final int MAX_RETRY_NUM = 5;

    public static final int MODEL_TYPE_LEARN_VIDEO = 1;
    public static final int MODEL_TYPE_NORMAL_VIDEO = 2;
    public static final int MODEL_TYPE_PHOTO = 3;
    public static final int MODEL_TYPE_INFO = 4;
    public static final int MODEL_TYPE_LOCAL_VIDEO = 5;

    public static final int DOWNLOAD_FILE_TYPE_VIDEO = 1;
    public static final int DOWNLOAD_FILE_TYPE_PHOTO = 2;
    public static final int DOWNLOAD_FILE_TYPE_AUDIO = 3;

    public static final int PROGRESS_STATUS_WAITING_DOWNLOAD_COVER = 1;
    public static final int PROGRESS_STATUS_DOWNLOADING_COVER = 2;
    public static final int PROGRESS_STATUS_DOWNLOAD_COVER_FINISHED = 3;
    public static final int PROGRESS_STATUS_DOWNLOAD_COVER_FAILED = 4;
    public static final int PROGRESS_STATUS_WAITING_DOWNLOAD = 5;
    public static final int PROGRESS_STATUS_DOWNLOADING = 6;
    public static final int PROGRESS_STATUS_DOWNLOAD_FINISHED = 7;
    public static final int PROGRESS_STATUS_DOWNLOAD_FAILED = 8;

    public static final int MAX_DOWNLOAD_THREAD = 10;

    public static final String ACTION_DOWNLOAD_UPDATE = "com.aiyige.action.ACTION_DOWNLOAD_UPDATE";
    public static final String ACTION_DOWNLOAD_PROGRESS_STATUS_UPDATE = "com.aiyige.action.ACTION_DOWNLOAD_PROGRESS_STATUS_UPDATE";
    public static final String ACTION_DOWNLOAD_PLAY_HISTORY_UPDATE = "com.aiyige.action.ACTION_DOWNLOAD_PLAY_HISTORY_UPDATE";

    public static final String DOWNLOAD_DIR = MyConfig.AIYIGE_ROOT_DIR + ".download" + File.separator;
    public static final String NOMEDIA = DOWNLOAD_DIR + ".nomedia";
    public static final String PHOTO_DIR = MyConfig.AIYIGE_ROOT_DIR + "photo" + File.separator;

    public static void createStage() {
        RxFileTool.createOrExistsDir(DOWNLOAD_DIR);
        RxFileTool.createOrExistsFile(NOMEDIA);
    }

    public static void clearStage() {
        RxFileTool.deleteFilesInDir(DOWNLOAD_DIR);
        RxFileTool.createOrExistsFile(NOMEDIA);
    }

    public static void recordPlayHistory(String modelId, int fileId, long playPosition) {
        try {
            List<DownloadFile> downloadFileList = DownloadFileDao.getDao()
                    .queryBuilder()
                    .where()
                    .eq(DownloadFile.PARENT_ID_FIELD, modelId)
                    .and()
                    .ne(DownloadFile.CONTROL_OPTION_FIELD, DownloadUtil.CONTROL_OPTION_DELETE_RECORD_ONLY)
                    .and()
                    .ne(DownloadFile.CONTROL_OPTION_FIELD, DownloadUtil.CONTROL_OPTION_DELETE)
                    .query();
            int playIndex = -1;
            for (int i = 0; i < downloadFileList.size(); ++i) {
                if (downloadFileList.get(i).getId() == fileId) {
                    playIndex = i;
                    break;
                }
            }
            UpdateBuilder<DownloadModel, String> updateBuilder = DownloadModelDao.getDao().updateBuilder();
            updateBuilder.updateColumnValue(DownloadModel.PLAY_INDEX, playIndex);
            updateBuilder.updateColumnValue(DownloadModel.PLAY_POSITION, playPosition);
            updateBuilder.where().eq(DownloadModel.ID_FIELD, modelId);
            updateBuilder.update();
            sendDownloadPlayHistroyUpdateBroadcast();
        } catch (Exception e) {

        }
    }

    public static String downloadCover(String url) throws Exception {
        createStage();
        Bitmap coverBitmap = Glide.with(MyApp.getAppContext())
                .asBitmap()
                .load(url)
                .apply(RequestOptions.centerInsideTransform())
                .submit()
                .get();
        String coverLocalPath = DOWNLOAD_DIR + UUIDUtil.generate() + ".jpg";
        FileOutputStream fileOutputStream = null;
        Exception catchException = null;
        try {
            File outputFile = new File(coverLocalPath);
            fileOutputStream = new FileOutputStream(outputFile);
            coverBitmap.compress(Bitmap.CompressFormat.JPEG, 80, fileOutputStream);
        } catch (Exception e) {
            catchException = e;
        } finally {
            try {
                fileOutputStream.close();
            } catch (Exception ex) {
                catchException = ex;
            }
        }
        if (catchException != null) {
            throw catchException;
        }
        return coverLocalPath;
    }

    public static void sendDownloadUpdateBroadcast() {
        MyApp.getAppContext().sendBroadcast(new Intent(ACTION_DOWNLOAD_UPDATE));
    }

    public static void sendDownloadProgressStatusUpdateBroadcast() {
        MyApp.getAppContext().sendBroadcast(new Intent(ACTION_DOWNLOAD_PROGRESS_STATUS_UPDATE));
    }

    public static void sendDownloadPlayHistroyUpdateBroadcast() {
        MyApp.getAppContext().sendBroadcast(new Intent(ACTION_DOWNLOAD_PLAY_HISTORY_UPDATE));
    }

    public static void downloadPhoto(final FragmentActivity activity, String photoUrl) {
        RxFileTool.createOrExistsDir(PHOTO_DIR);
        new AsyncTask<String, Object, Object>() {
            LoadingDialog loadingDialog;

            @Override
            protected void onPreExecute() {
                loadingDialog = LoadingDialog.newBuilder()
                        .with(activity)
                        .show();
            }

            @Override
            protected Object doInBackground(String... urls) {
                try {
                    File file = Glide.with(MyApp.getAppContext())
                            .downloadOnly()
                            .load(urls[0])
                            .submit()
                            .get();
                    String fileExtension = FileUtil.detectFileExtension(file.getAbsolutePath());
                    String outputPath = PHOTO_DIR + UUIDUtil.generate() + fileExtension;
                    Exception catchException = null;
                    try {
                        File outputFile = new File(outputPath);
                        RxFileTool.copyFile(file, outputFile);
                    } catch (Exception e) {
                        catchException = e;
                    }
                    if (catchException != null) {
                        throw catchException;
                    }
                    return outputPath;
                } catch (Exception e) {
                    return e;
                }
            }

            @Override
            protected void onPostExecute(Object o) {
                loadingDialog.dismiss();
                if (o instanceof Exception) {
                    ToastX.show(((Exception) o).getMessage());
                } else {
                    MediaUtil.scanMedia((String) o);
                    ToastX.show(String.format(StringUtils.getString(R.string.photo_download_to_dir), (String) o));
                }
            }
        }.execute(photoUrl);
    }

    public static void downloadVideo(final FragmentActivity activity, final String momentId, final String source, final String resourceId) {
        if (!RxNetTool.isWifi(activity) && ConfigUltis.isEnableGprsNotification()) {
            GprsNotificationDialogUtil.createDownloadBuilder(activity)
                    .setPositiveButton(R.string.confirm_download, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            _downloadVideo(activity, momentId, source, resourceId);
                        }
                    })
                    .setNegativeButton(R.string.cancel, null)
                    .create()
                    .show();
        } else {
            _downloadVideo(activity, momentId, source, resourceId);
        }
    }

    protected static void _downloadVideo(final FragmentActivity activity, String momentId, String source, String resourceId) {
        new AsyncTask<Object, Object, Object>() {
            LoadingDialog loadingDialog;
            String momentId;
            String source;
            String resourceId;

            @Override
            protected void onPreExecute() {
                loadingDialog = LoadingDialog.newBuilder()
                        .with(activity)
                        .show();
            }

            @Override
            protected Object doInBackground(Object... objects) {
                momentId = (String) objects[0];
                source = (String) objects[1];
                resourceId = (String) objects[2];
                try {
                    Response<ResponseBody> response = ApiManager.getService().getMoment(momentId, source, resourceId).execute();
                    if (response.code() != ResponseCode.OK) {
                        throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                    }
                    String json = RetrofitUtil.getResponseBodyAsString(response);
                    Moment moment = JSON.parseObject(json, Moment.class);
                    Moment record = new Moment(moment);
                    int modelType;
                    List<SingleVideo> singleVideoList = new LinkedList<>();

                    switch (record.getSubjectIndex()) {
                        case Moment.SUBJECT_VIDEO_COURSE_INDEX: {
                            modelType = DownloadUtil.MODEL_TYPE_LEARN_VIDEO;
                            VideoCourse videoCourse = JSON.parseObject(record.getMoreBackup(), VideoCourse.class);
                            singleVideoList.addAll(videoCourse.getVideos());
                            break;
                        }
                        case Moment.SUBJECT_VIDEO_INDEX: {
                            modelType = MODEL_TYPE_NORMAL_VIDEO;
                            Video video = JSON.parseObject(record.getMoreBackup(), Video.class);
                            singleVideoList.addAll(video.getVideos());
                            break;
                        }
                        default:
                            throw new Exception("错误的类型");
                    }

                    if (ListUtil.isEmpty(singleVideoList)) {
                        throw new Exception("视频列表为空");
                    }

                    final DownloadModel downloadModel = DownloadModel.newBuilder()
                            .downloadDate(System.currentTimeMillis())
                            .modelType(modelType)
                            .authorAvatar(record.getCreatorBackup().getAvatar())
                            .authorId(record.getCreatorBackup().getId())
                            .authorName(record.getCreatorBackup().getName())
                            .controlOption(DownloadUtil.CONTROL_OPTION_DOWNLOAD)
                            .coverRemoteUrl(ListUtil.isEmpty(record.getCover()) ? "" : record.getCover().get(0))
                            .id(UUIDUtil.generate())
                            .goodsId(record.getId())
                            .introduction(record.getSummary())
                            .price(record.getCommodityBackup().getPrice())
                            .progressStatus(DownloadUtil.PROGRESS_STATUS_WAITING_DOWNLOAD_COVER)
                            .releaseDate(record.getCreateTime())
                            .userId(AccountUtil.getCurrentUser().getId())
                            .mediaNum(record.getMediaSummary().getCount())
                            .title(record.getTitle())
                            .build();
                    final List<DownloadFile> downloadFileList = new LinkedList<>();
                    for (SingleVideo videoEntity : singleVideoList) {
                        if (TextUtils.isEmpty(videoEntity.getUrl())) continue;
                        downloadFileList.add(DownloadFile.newBuilder()
                                .controlOption(DownloadUtil.CONTROL_OPTION_DOWNLOAD)
                                .coverRemoteUrl(videoEntity.getCover())
                                .duration(videoEntity.getDuration())
                                .userId(AccountUtil.getCurrentUser().getId())
                                .fileRemoteUrl(videoEntity.getUrl())
                                .fileLocalUrl(DownloadUtil.DOWNLOAD_DIR + UUIDUtil.generate())
                                .title(videoEntity.getTitle())
                                .fileType(DownloadUtil.DOWNLOAD_FILE_TYPE_VIDEO)
                                .progressStatus(DownloadUtil.PROGRESS_STATUS_WAITING_DOWNLOAD_COVER)
                                .parentId(downloadModel.getId())
                                .build());
                    }


                    return TransactionManager.callInTransaction(DBHelper.getInstance().getConnectionSource(), new Callable<Object>() {
                        @Override
                        public Object call() throws Exception {
                            DownloadModelDao.getDao().create(downloadModel);
                            for (DownloadFile downloadFile : downloadFileList) {
                                DownloadFileDao.getDao().create(downloadFile);
                            }
                            return null;
                        }
                    });

                } catch (Exception e) {
                    return e;
                }
            }

            @Override
            protected void onPostExecute(Object o) {
                loadingDialog.dismiss();
                if (o instanceof Exception) {
                    ToastX.show(((Exception) o).getMessage());
                } else {
                    ToastX.show(R.string.download);
                    DownloadUtil.startDownload();
                }
            }
        }.execute(momentId, source, resourceId);
    }


    /**
     * 迁移工具（写入）
     *
     * @param list
     */
    public static void removalDownloadVideo(final List<VideoCacheParentModel> list) {

        if (ListUtil.isEmpty(list)) {
            return;
        }
        for (VideoCacheParentModel cacheParentModel : list) {

            new AsyncTask<VideoCacheParentModel, Object, Object>() {
                VideoCacheParentModel model;

                @Override
                protected void onPreExecute() {
                }

                @Override
                protected Object doInBackground(VideoCacheParentModel... videoCacheParentModels) {
                    model = videoCacheParentModels[0];
                    try {
                        final DownloadModel downloadModel = getDownloadModel(model);
                        return TransactionManager.callInTransaction(DBHelper.getInstance().getConnectionSource(), new Callable<Object>() {
                            @Override
                            public Object call() throws Exception {
                                DownloadModelDao.getDao().create(downloadModel);
                                List<DownloadFile> downloadFileList = getDownloadFileList(model,downloadModel);
                                for (DownloadFile downloadFile : downloadFileList) {
                                    int i = DownloadFileDao.getDao().create(downloadFile);
                                    if (i > 0) {
                                        Log.i("removalFailed", i + "");
                                    } else {
                                        Log.e("removalFailed", i + "");
                                    }
                                }
                                List<DownloadFile> list1 = DownloadFileDao.getDao().queryBuilder()
                                        .where()
                                        .eq(DownloadFile.PARENT_ID_FIELD, downloadModel.getId())
                                        .and()
                                        .ne(DownloadFile.CONTROL_OPTION_FIELD, DownloadUtil.CONTROL_OPTION_DELETE)
                                        .and()
                                        .ne(DownloadFile.CONTROL_OPTION_FIELD, DownloadUtil.CONTROL_OPTION_DELETE_RECORD_ONLY)
                                        .query();
                                if (list1 != null) {
                                    Log.e("",list1.size()+"");
                                }


                                return null;
                            }
                        });

                    } catch (Exception e) {
                        return e;
                    }


                }

                @Override
                protected void onPostExecute(Object o) {
                    if (o instanceof Exception) {
//                        ToastX.show(((Exception) o).getMessage());
                    } else {
//                        ToastX.show(R.string.download);
//                        DownloadUtil.startDownload();
                    }

                    EventBus.getDefault().post(new EventRemovalSuccess());

                }
            }.execute(cacheParentModel);
        }




    }


    /**
     * 模型转换
     * @param model
     * @return
     */
    private static DownloadModel getDownloadModel(VideoCacheParentModel model) {
        if (model == null || ListUtil.isEmpty(model.getChildModelList())) {
            return null;
        }
        User user = AccountUtil.getCurrentUser();
        final DownloadModel downloadModel = DownloadModel.newBuilder()
                .downloadDate(model.isAllDownloaded()?formatLongTime(model.getCreateTime()):System.currentTimeMillis())
                .modelType(model.getTypeId() == VideoCacheParentModel.TYPE_COURSE_VIDEO ? DownloadUtil.MODEL_TYPE_LEARN_VIDEO : DownloadUtil.MODEL_TYPE_NORMAL_VIDEO)
                .authorAvatar(user.getAvatar())
                .authorId(user.getId())
                .authorName(user.getAccount())
                .controlOption(DownloadUtil.CONTROL_OPTION_DOWNLOAD)
                .coverRemoteUrl(model.getCover())
                .id(UUIDUtil.generate())
//                .goodsId(model.getVideoId())
                .introduction(model.getDescription())
//                .price(model.get)
                .progressStatus(model.isAllDownloaded() ? DownloadUtil.PROGRESS_STATUS_DOWNLOAD_FINISHED : DownloadUtil.PROGRESS_STATUS_WAITING_DOWNLOAD_COVER)
                .releaseDate(formatLongTime(model.getCreateTime()))
                .userId(AccountUtil.getCurrentUser().getId())
                .mediaNum(model.getChildModelList().size())
                .title(model.getTitle())
                .build();
        return downloadModel;

    }

    /**
     * 模型转换
     * @param model
     * @param downloadModel
     * @return
     */
    private static List<DownloadFile> getDownloadFileList(VideoCacheParentModel model,DownloadModel downloadModel) {
        if (model == null || ListUtil.isEmpty(model.getChildModelList())) {
            return null;
        }
        final List<DownloadFile> downloadFileList = new LinkedList<>();
        for (VideoCacheChildModel childModel : model.getChildModelList()) {
//            if (TextUtils.isEmpty(childModel.getUrl()) || TextUtils.isEmpty(childModel.getPath())) {
//                continue;
//            }
            downloadFileList.add(DownloadFile.newBuilder()
                    .controlOption(DownloadUtil.CONTROL_OPTION_PAUSE)
                    .coverRemoteUrl(childModel.getImageUrl())
                    .duration(childModel.getDuration())
                    .userId(AccountUtil.getCurrentUser().getId())
                    .fileRemoteUrl(childModel.getUrl())
                    .fileLocalUrl(childModel.isDownloaded()?childModel.getPath():(DownloadUtil.DOWNLOAD_DIR + UUIDUtil.generate()))
                    .title(childModel.getTitle())
                    .fileType(DownloadUtil.DOWNLOAD_FILE_TYPE_VIDEO)
                    .parentId(downloadModel.getId())
                    .progressStatus(childModel.isDownloaded() ? DownloadUtil.PROGRESS_STATUS_DOWNLOAD_FINISHED : DownloadUtil.PROGRESS_STATUS_WAITING_DOWNLOAD_COVER)
                    .build());
        }
        return downloadFileList;

    }


    public static DownloadModel getDownloadModelByGoodsId(String goodsId) {
        scanDownload();
        try {
            QueryBuilder<DownloadModel, String> queryBuilder = DownloadModelDao.getDao().queryBuilder();
            List<DownloadModel> downloadModelList = queryBuilder.where()
                    .ne(DownloadModel.CONTROL_OPTION_FIELD, DownloadUtil.CONTROL_OPTION_DELETE)
                    .and()
                    .ne(DownloadModel.CONTROL_OPTION_FIELD, DownloadUtil.CONTROL_OPTION_DELETE_RECORD_ONLY)
                    .and()
                    .eq(DownloadModel.USER_ID_FIELD, AccountUtil.getCurrentUser().getId())
                    .and()
                    .eq(DownloadModel.GOODS_ID_FIELD, goodsId)
                    .query();
            return downloadModelList.get(0);
        } catch (Exception e) {
            return null;
        }
    }


    public static List<DownloadFile> getDownloadFileByGoodsId(String goodsId) {
        try {
            DownloadModel downloadModel = getDownloadModelByGoodsId(goodsId);
            QueryBuilder<DownloadFile, Integer> queryBuilder = DownloadFileDao.getDao().queryBuilder();
            List<DownloadFile> downloadFileList = queryBuilder.where()
                    .ne(DownloadModel.CONTROL_OPTION_FIELD, DownloadUtil.CONTROL_OPTION_DELETE)
                    .and()
                    .ne(DownloadModel.CONTROL_OPTION_FIELD, DownloadUtil.CONTROL_OPTION_DELETE_RECORD_ONLY)
                    .and()
                    .eq(DownloadFile.PARENT_ID_FIELD, downloadModel.getId())
                    .query();
            return downloadFileList;
        } catch (Exception e) {
            return null;
        }
    }


    public static void scanDownload() {
        try {
            QueryBuilder<DownloadFile, Integer> queryBuilder = DownloadFileDao.getDao().queryBuilder();
            List<DownloadFile> downloadFileList = queryBuilder.where()
                    .ne(DownloadFile.CONTROL_OPTION_FIELD, DownloadUtil.CONTROL_OPTION_DELETE)
                    .and()
                    .ne(DownloadFile.CONTROL_OPTION_FIELD, DownloadUtil.CONTROL_OPTION_DELETE_RECORD_ONLY)
                    .and()
                    .eq(DownloadFile.PROGRESS_STATUS_FIELD, DownloadUtil.PROGRESS_STATUS_DOWNLOAD_FINISHED)
                    .query();
            for (DownloadFile downloadFile : downloadFileList) {
                if (!RxFileTool.isFileExists(downloadFile.getFileLocalUrl())) {
                    UpdateBuilder<DownloadFile, Integer> updateBuilder = DownloadFileDao.getDao().updateBuilder();
                    updateBuilder.updateColumnValue(DownloadFile.CONTROL_OPTION_FIELD, DownloadUtil.CONTROL_OPTION_DELETE_RECORD_ONLY);
                    updateBuilder.where().eq(DownloadFile.ID_FIELD, downloadFile.getId());
                    updateBuilder.update();
                }
            }

            QueryBuilder<DownloadModel, String> downloadModelQueryBuilder = DownloadModelDao.getDao().queryBuilder();
            List<DownloadModel> downloadModelList = downloadModelQueryBuilder.where()
                    .ne(DownloadModel.CONTROL_OPTION_FIELD, DownloadUtil.CONTROL_OPTION_DELETE)
                    .and()
                    .ne(DownloadModel.CONTROL_OPTION_FIELD, DownloadUtil.CONTROL_OPTION_DELETE_RECORD_ONLY)
                    .query();
            for (DownloadModel downloadModel : downloadModelList) {
                List<DownloadFile> fileList = DownloadFileDao.getDao().queryBuilder()
                        .where()
                        .ne(DownloadFile.CONTROL_OPTION_FIELD, DownloadUtil.CONTROL_OPTION_DELETE)
                        .and()
                        .ne(DownloadFile.CONTROL_OPTION_FIELD, DownloadUtil.CONTROL_OPTION_DELETE_RECORD_ONLY)
                        .and()
                        .eq(DownloadFile.PARENT_ID_FIELD, downloadModel.getId())
                        .query();
                if (ListUtil.isEmpty(fileList)) {
                    UpdateBuilder<DownloadModel, String> updateBuilder = DownloadModelDao.getDao().updateBuilder();
                    updateBuilder.updateColumnValue(DownloadModel.CONTROL_OPTION_FIELD, DownloadUtil.CONTROL_OPTION_DELETE_RECORD_ONLY);
                    updateBuilder.where().eq(DownloadModel.ID_FIELD, downloadModel.getId());
                    updateBuilder.update();
                }
            }
        } catch (Exception e) {
            Timber.e("scanDownload:" + Log.getStackTraceString(e));
        }
    }


    public static void startDownload() {
        DownloadService.startDownload(MyApp.getAppContext());
    }


    public static void pauseAll() {
        try {
            UpdateBuilder<DownloadFile, Integer> updateBuilder = DownloadFileDao.getDao().updateBuilder();
            updateBuilder.updateColumnValue(DownloadFile.CONTROL_OPTION_FIELD, DownloadUtil.CONTROL_OPTION_PAUSE);
            updateBuilder.where()
                    .eq(DownloadFile.USER_ID_FIELD, AccountUtil.getCurrentUser().getId())
                    .and()
                    .ne(DownloadFile.CONTROL_OPTION_FIELD, DownloadUtil.CONTROL_OPTION_DELETE)
                    .and()
                    .ne(DownloadFile.CONTROL_OPTION_FIELD, DownloadUtil.CONTROL_OPTION_DELETE_RECORD_ONLY);
            updateBuilder.update();
        } catch (Exception e) {

        }

        try {
            UpdateBuilder<DownloadModel, String> updateBuilder = DownloadModelDao.getDao().updateBuilder();
            updateBuilder.updateColumnValue(DownloadModel.CONTROL_OPTION_FIELD, DownloadUtil.CONTROL_OPTION_PAUSE);
            updateBuilder.where()
                    .eq(DownloadModel.USER_ID_FIELD, AccountUtil.getCurrentUser().getId())
                    .and()
                    .ne(DownloadModel.CONTROL_OPTION_FIELD, DownloadUtil.CONTROL_OPTION_DELETE)
                    .and()
                    .ne(DownloadModel.CONTROL_OPTION_FIELD, DownloadUtil.CONTROL_OPTION_DELETE_RECORD_ONLY);
            updateBuilder.update();
        } catch (Exception e) {

        }


    }


    /**
     * 把 2018-02-17 14:47:54 转换成long
     *
     * @param str
     * @return
     */
    public static long formatLongTime(String str) {
        long timeLong = System.currentTimeMillis();
        SimpleDateFormat yyyyMMddHHmmssFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = yyyyMMddHHmmssFormat.parse(str);
            timeLong = date.getTime();
        } catch (Exception e) {

        }
        return timeLong;
    }


}
